<?php

/*
Plugin Name: WP Showroom
Plugin URI: http://animalbeach.net/aniga/
Description: Picture Gallery implemented in the WP framework.
Author: Michael Naab
Version: 0.8a1
Author URI: http://www.animalbeach.net/
*/


/*

	WP Showroom
	------------

	@file 		wpsr.php
	@version 	0.1b1
	@date 		2009-03-23 21:47:54 +0100 (Mon, 23 Mar 2009)
	@author 	Michael Naab <michael.naab@googlemail.com>

	Copyright (c) 2009 Michael Naab <http://www.animalbeach.net>
	
	
	todo:
	- gesamtzahl pictures für alben (cronjob? )
	- navigation
	- pages
	- flash upload
	- tags
	- random thingy
	- album order mit javascript + save button
	- album Bild + Titel auf Manage Screen
	- comments pro bild (-> comment hooks + wpsr_pic DB)
*/



define('WPSR_ACCESS', true);
define('WPSR_VERSION', 'v0.8a1');



require_once 'config.php';



/**
 * WPsr class.
 * 
 */
class WPsr {
	
	/**
	 * error
	 * 
	 * (default value: array())
	 * 
	 * @var array
	 * @access public
	 */
	var $error = array();
	
	
	/**
	 * message
	 * 
	 * (default value: array())
	 * 
	 * @var array
	 * @access public
	 */
	var $message = array();
	
	
	/**
	 * user
	 * 
	 * (default value: NULL)
	 * 
	 * @var mixed
	 * @access private
	 */
	private  $user = NULL;
	
	
	/**
	 * obj
	 * 
	 * (default value: NULL)
	 * 
	 * @var mixed
	 * @access public
	 */
	var $obj = NULL;
	
	
	/**
	 * path
	 * 
	 * (default value: NULL)
	 * 
	 * @var mixed
	 * @access public
	 */
	var $path = NULL;
	
	
	/**
	 * albums
	 * 
	 * (default value: NULL)
	 * 
	 * @var mixed
	 * @access public
	 */
	var $albums = NULL;
	
	
	/**
	 * pictures
	 * 
	 * (default value: NULL)
	 * 
	 * @var mixed
	 * @access public
	 */
	var $pictures = NULL;
	
	
	/**
	 * style
	 * 
	 * (default value: NULL)
	 * 
	 * @var mixed
	 * @access public
	 */
	var $style = NULL;
	
	
	/**
	 * current
	 * 
	 * (default value: NULL)
	 * 
	 * @var mixed
	 * @access private
	 */
	private $current = NULL;
	
	
	/**
	 * maxpic
	 * 
	 * (default value: NULL)
	 * 
	 * @var mixed
	 * @access private
	 */
	private $maxpic = NULL;



	/**
	 * exif
	 * 
	 * (default value: array())
	 * 
	 * @var array
	 * @access public
	 */
	var $exif = array();


	

	/**
	 * err function.
	 * 
	 * @access public
	 * @return array
	 */
	function err() {
		$error = array(
			'0' => 'Sorry, dunno.. Unknown error!',
			'1' => 'Error: WP-ID does not match!',
			'2' => 'Error: Bad ID. Picture not found!',
			'3' => 'Error: Bad ID. Album not found!',
			'4' => 'Error: You are not allowed to view this page!',
			'5' => 'Error: You are not allowed to view this page inside this path!',
			'6' => 'Error: You are not allowed to edit this Album!',
			'7' => 'Error: You are not allowed to add/move an Album here!',
			'8' => 'Error: You are not allowed to manage this ID!',
			'9' => 'Error: You are not allowed to delete ths Album!',
			'10' => 'Error: You are not allowed to edit this Picture!',
			'11' => 'Error: You are not allowed to move a Picture here!',
			'12' => 'Error: You are not allowed to delete this Picture!',
			'13' => 'Error: You are not allowed to use this Picture!',
			'404' => 'ups. Albums or Picture not found!'
		);
		foreach ($this->error as &$value) {
			$value = strtr($value, $error);
		}
		return $this->error;
	}





	/**
	 * msg function.
	 * 
	 * @access public
	 * @return array
	 */
	function msg() {
		$message = array(
			'0' => 'something happend!',
			'1' => 'Warning: Duplicated Album title!',
			'2' => 'Warning: Album title required!',
			'3' => 'Album saved!',
			'4' => 'Album not saved!',
			'5' => 'Warning: Could not move files!',
			'6' => 'Pictures successfully assigned!',
			'7' => 'Warning: No Album to assign pictures found. Done nothing!',
			'8' => 'Pictures unassigned from Album!',
			'9' => 'Warning: Could not delete picture!',
			'10' => 'Warning: Could not create Upload Directory!',
			'11' => 'Warning: Could not create temporary Upload Directory!',
			'12' => 'Picture saved!',
			'13' => 'Picture not saved!',
			'14' => 'Pictures saved!',
			'15' => 'Pictures not saved!',
			'16' => 'Picture(s) deleted!',
			'17' => 'Warning: Picture(s) not deleted!'
		);
		foreach ($this->message as &$value) {
			$value = strtr($value, $message);
		}
		return $this->message;
	}





	/**
	 * init function.
	 * 
	 * @access public
	 * @return void
	 */
	function init() {
		if (WPSR_BASE != get_the_ID() ) {
			$this->error[] = '1';
		}

		$this->WPsrUser();
		$this->getObj();
		$this->SecurityManager();
		$this->makeGallery();

	}





	/**
	 * getObj function.
	 * 
	 * @access private
	 * @return void
	 */
	private function getObj() {

		$uri = $_SERVER['REQUEST_URI'];

		$uri = trim($uri, '/');
		$home_path = parse_url(get_option('home'));
		$home_path = $home_path['path'];
		$uri = str_replace($home_path, '', $uri);
		$uri = explode("/", $uri);

		
		/**
		 * $this->style		1 => gallery index
		 *					2 => single pic
		 *					3 => smug / thumb album page
		 *					4 => thumbnail / child page
		 *					5 => slideshow
		 */

		if (count($uri) == 1 && $uri[0] == WPSR_BASE_URI) {
			/**
			 * Gallery Index
			 */
			$this->obj = $this->getAlbByUri('root');
			$this->style = 1;
		}
		elseif ($uri[1] == WPSR_SHOW_URI) {
			/**
			 * Permalink to Picture
			 */
			$this->obj = $this->getPicById((int) $uri[2]);
			$this->style = 2;
		}
		elseif ($uri[2] == WPSR_SHOW_URI) {
			/**
			 * Picture -> get picture ID and album URI
			 */
			$this->obj = $this->getPicByIdUri((int) $uri[3], $uri[1]);
			$this->style = 2;
		}
		elseif ($uri[2] == WPSR_PAGE_URI) {
			/**
			 * Paged Album -> get album URI and set Page Number
			 */
			$this->obj = $this->getAlbByUri($uri[1]);
			$this->obj->page = (int) $uri[3];
			$this->style = 3;
		}
		elseif ($uri[2] == WPSR_THUMB_URI) {
			/**
			 * Thumbnail Page -> get album URI and set Page Number
			 */
			$this->obj = $this->getAlbByUri($uri[1]);
			$this->obj->page = (int) $uri[3];
			$this->style = 4;
		}
		elseif ($uri[2] == WPSR_SLIDE_URI) {
			/**
			 * Slideshow Page -> $this->obj-page = start PID
			 */
			$this->obj = $this->getAlbByUri($uri[1]);
			$this->obj->page = (int) $uri[3];
			$this->style = 5;
		}
		else {
			/**
			 * Album -> get album URI
			 */
			$this->obj = $this->getAlbByUri($uri[1]);
			$this->obj->page = 1;
			$this->style = 3;
		}
		
		/**
		 * Get path to object
		 */
		if ($this->obj->id && $this->obj->type == 1) {
			$this->path = $this->getPath($this->obj->paid);
		}
		elseif ($this->obj->id && $this->obj->type == 2) {
			$this->path = $this->getPath($this->obj->aid);
		}
		else {
			$this->error[] = '3';
		}
	}





	/**
	 * getPicByIdUri function.
	 * 
	 * @access public
	 * @param int $id
	 * @param string $uri
	 * @return object
	 */
	function getPicByIdUri($id, $uri) {
		global $wpdb;
		$q = "SELECT r.id, p.pid, p.aid, a.paid, p.path, p.file, p.caption, p.width, p.height, p.hits, a.title, a.uri, a.description, r.date, r.owner, r.level, r.type, a.com
			FROM ".WPSR_DB_P." p
			LEFT JOIN ".WPSR_DB_R." r ON p.pid = r.id
			LEFT JOIN ".WPSR_DB_A." a ON a.aid = p.aid
			WHERE a.uri = '$uri'
			AND p.pid = '$id'
			LIMIT 1";
		$q = $wpdb->prepare($q);
		$obj = $wpdb->get_row($q);
		if ( !$obj->id ) {
			$this->error[] = '2';
		}
		return $obj;
	}





	/**
	 * getPicById function.
	 * 
	 * @access public
	 * @param int $id
	 * @return object
	 */
	function getPicById($id) {
		global $wpdb;
		$q = "SELECT r.id, p.pid, p.aid, a.paid, p.path, p.file, p.caption, p.width, p.height, p.hits, a.title, a.uri, a.description, r.date, r.owner, r.level, r.type, a.com
			FROM ".WPSR_DB_P." p
			LEFT JOIN ".WPSR_DB_R." r ON p.pid = r.id
			LEFT JOIN ".WPSR_DB_A." a ON a.aid = p.aid
			WHERE p.pid = '$id'
			LIMIT 1";
		$q = $wpdb->prepare($q);
		$obj = $wpdb->get_row($q);
		if ( !$obj->id ) {
			$this->error[] = '2';
		}
		return $obj;
	}





	/**
	 * getAlbByUri function.
	 * 
	 * @access public
	 * @param string $uri
	 * @return object
	 */
	function getAlbByUri($uri) {
		global $wpdb;
		$q = "SELECT a.aid, r.id, a.paid, a.title, a.uri, a.description, a.ord, a.com, r.type, r.date, r.owner, r.level, c.paid AS hasChild, a.cover, a.meta
			FROM ".WPSR_DB_A." a
			LEFT JOIN ".WPSR_DB_R." r ON r.id = a.aid
			LEFT JOIN ".WPSR_DB_A." c ON c.paid = a.aid
			WHERE a.uri = '$uri'
			LIMIT 1";
		$q = $wpdb->prepare($q);
		$obj = $wpdb->get_row($q);
		if ( !$obj->id ) {
			$this->error[] = '3';
		}
		return $obj;
	}





	/**
	 * getAlbById function.
	 * 
	 * @access public
	 * @param int $id
	 * @return object
	 */
	function getAlbById($id) {
		global $wpdb;
		$q = "SELECT a.aid, r.id, a.paid, a.title, a.uri, a.description, a.ord, a.com, r.type, r.date, r.owner, r.level, c.paid AS hasChild, a.cover, a.meta
			FROM ".WPSR_DB_A." a
			LEFT JOIN ".WPSR_DB_R." r ON r.id = a.aid
			LEFT JOIN ".WPSR_DB_A." c ON c.paid = a.aid
			WHERE a.aid = '$id'
			LIMIT 1";
		$q = $wpdb->prepare($q);
		$obj = $wpdb->get_row($q);
		if ( !$obj->id ) {
			$this->error[] = '3';
		}
		return $obj;
	}





	/**
	 * getPath function.
	 * 
	 * @access public
	 * @param int $id
	 * @return object
	 */
	function getPath($id) {
		global $wpdb;

		$q = "SELECT r.id, r.level, r.owner, r.type, a.aid, a.paid, a.title, a.uri, a.description
			FROM ".WPSR_DB_R." r
			LEFT JOIN ".WPSR_DB_A." a ON r.id = a.aid
			WHERE r.id = '$id'";
		$q = $wpdb->prepare($q);
		$row = $wpdb->get_row($q);

		$path = array();
		if ($row->paid != '') {
			$row->isOwner = $this->getOwner($row->owner);
			$path[] = $row;
			$path = array_merge($this->getPath($row->paid), $path);
		}
		return $path;
	}





	/**
	 * WPsrUser function.
	 * 
	 * @access public
	 * @return void
	 */
	function WPsrUser() {
		global $current_user;
		get_currentuserinfo();
		/**
		 * get Userlevel of current User
		 */
		if ($current_user->user_level != '') {
			$this->user = $current_user->user_level;
		}
		else {
			$this->user = 0;
		}
	}





	/**
	 * SecurityManager function.
	 * 
	 * @access public
	 * @param bool $dopath. (default: true)
	 * @return void
	 */
	function SecurityManager($dopath = true) {
		if ($this->obj->id) {
			/**
			 * check if current User is Owner (doesnt matter if he has not enough rights!)
			 */
			$this->obj->isOwner = $this->getOwner($this->obj->owner);
			/**
			 * check Object and path
			 */
			if ( $this->checkObj($this->obj) ) {
				$this->error[] = '4';
			}
			if ($dopath) {
				if ( $this->checkPath($this->path) ) {
					$this->error[] = '5';
				}
			}
		}
		else {
			$this->error[] = '3';
		}
	}





	/**
	 * checkObj function.
	 * 
	 * @access public
	 * @param object $obj
	 * @return bool
	 */
	function checkObj($obj) {
		if ( $obj->level > $this->user ) {
			return true;
		}
		else {
			return false;
		}
	}





	/**
	 * checkPath function.
	 * 
	 * @access public
	 * @param object $chkpath
	 * @return bool
	 */
	function checkPath($chkpath) {
		foreach ($chkpath as $path) {
			if ( $path->level > $this->user ) {
				return true;
			}
		}
		return false;
	}





	/**
	 * getOwner function.
	 * 
	 * @access public
	 * @param int $owner
	 * @return int
	 */
	function getOwner($owner) {
		global $current_user;
		get_currentuserinfo();
		if ($this->user >= WPSR_ADMIN) {
			return 2;
		}
		elseif ($owner == $current_user->ID) {
			return 1;
		}
		else {
			return 0;
		}
	}





	/**
	 * makeGallery function.
	 * 
	 * @access public
	 * @return void
	 */
	function makeGallery() {
		if ($this->obj->type == 1) {
			$this->makeAlbum();
		}
		elseif ($this->obj->type == 2) {
			$this->makePicture();
		}
		
		if ( count($this->error) > 0 ) {
			$this->error_output();
		}
		else {
			$this->output();
		}
	}





	/**
	 * makeAlbum function.
	 * 
	 * @access public
	 * @return void
	 */
	function makeAlbum() {
		$this->getPictures();
		$this->albums = $this->getAlbums($this->obj->id, 0, 0);
	}





	/**
	 * makePicture function.
	 * 
	 * @access public
	 * @return void
	 */
	function makePicture() {
		$this->getPictures();
	}





	/**
	 * getAlbCover function.
	 * 
	 * @access public
	 * @param obj $alb
	 * @param string $size
	 * @return string
	 */
	function getAlbCover($alb, $size) {
		if ($alb->cover === NULL) {
			return WPSR_PATH."gfx/blank.gif";
		}
		else {
			return WPSR_PATH.$size."/".$alb->cover;
		}
	}





	/**
	 * getAlbums function.
	 * 
	 * @access public
	 * @param int $parent
	 * @param int $level
	 * @param mixed $depth. (default: NULL)
	 * @param mixed $self. (default: NULL)
	 * @return object
	 */
	function getAlbums($parent, $level, $depth = NULL, $self = NULL) {
		global $wpdb;

		$q = "SELECT r.id, a.aid, a.paid, a.title, a.uri, a.description, a.ord, a.com, r.date, r.owner, r.level, COUNT( y.aid ) AS pics, SUM( y.hits ) AS hits, c.paid AS hasChild, a.cover, a.meta
			FROM  ".WPSR_DB_A." a
			LEFT JOIN ".WPSR_DB_R." r ON r.id = a.aid
			LEFT JOIN (
					SELECT p.aid, p.hits
					FROM ".WPSR_DB_P." p
					LEFT JOIN wpsr_ref x ON p.pid = x.id
					WHERE x.level <= ".$this->user."
				) y ON y.aid = a.aid
			LEFT JOIN ".WPSR_DB_A." c on c.paid = a.aid
			WHERE r.level <= ".$this->user."
			AND a.paid = ".$parent."
			GROUP BY a.aid
			ORDER BY a.ord DESC";
		$q = $wpdb->prepare($q);

		$result = $wpdb->get_results($q);
		$albums = array();
		foreach ($result as $alb) {
			$alb->isOwner = $this->getOwner($alb->owner);
			$alb->intend = $level+1;
			if ($self != $alb->id || $self === NULL) {
				$albums[] = $alb;
				if ($depth > $level || $depth === NULL) {
					$albums = array_merge($albums, $this->getAlbums($alb->aid, $level+1, $depth, $self));
				}
			}
		}
		return $albums;
	}





	/**
	 * getPictures function.
	 * 
	 * @access public
	 * @return object
	 */
	function getPictures() {
		global $wpdb;
		$q = $wpdb->prepare("SELECT * FROM ".WPSR_DB_P.", ".WPSR_DB_R." WHERE ".WPSR_DB_P.".aid = ".$this->obj->aid." AND ".WPSR_DB_R.".id = ".WPSR_DB_P.".pid AND ".WPSR_DB_R.".level <= ".$this->user." ORDER BY ".WPSR_DB_P.".file");
		$this->pictures = $wpdb->get_results($q);
		for ($i=0; $i < count($this->pictures); $i++) {
			$this->pictures[$i]->isOwner = $this->getOwner($this->pictures[$i]->owner);
		}
		return $this->pictures;
	}





	/**
	 * getPicturesByAid function.
	 * 
	 * @access public
	 * @param int $aid
	 * @param bool $level. (default: true)
	 * @return object
	 */
	function getPicturesByAid($aid, $level = true) {
		global $wpdb;
		$q = "SELECT * FROM ".WPSR_DB_P.", ".WPSR_DB_R." WHERE ".WPSR_DB_P.".aid = ".$aid." AND ".WPSR_DB_R.".id = ".WPSR_DB_P.".pid ";
		if ($level) {
			$q .= "AND ".WPSR_DB_R.".level <= ".$this->user;
		}
		$q .= " ORDER BY ".WPSR_DB_P.".file";
		$q = $wpdb->prepare($q);
		$this->pictures = $wpdb->get_results($q);
		for ($i=0; $i < count($this->pictures); $i++) {
			$this->pictures[$i]->isOwner = $this->getOwner($this->pictures[$i]->owner);
		}
		return $this->pictures;
	}





	/**
	 * output function.
	 * 
	 * @access public
	 * @return void
	 */
	function output() {

		if ($this->obj->id == 1) {
			$this->index();
		}
		elseif ($this->obj->type == 1) {
			$this->album();
		}
		elseif ($this->obj->type == 2) {
			$this->picture();
		}
		else {
			$this->error_output();
		}
	}





	/**
	 * index function.
	 * 
	 * @access public
	 * @return void
	 */
	function index() {
		include "templates/galleryindex.php";
		//$this->error_output();
	}





	/**
	 * album function.
	 * 
	 * @access public
	 * @return void
	 */
	function album() {
		if ($this->style == 3) {
			if ($this->obj->hasChild === NULL) {
				$this->smugstyle();
			}
			else {
				$this->thumbchilds();
			}
		}
		elseif ($this->style == 5) {
			$this->slideshow();
		}
		else {
			$this->thumbchilds();
		}
		//$this->error_output();
	}





	/**
	 * smugstyle function.
	 * 
	 * @access public
	 * @return void
	 */
	function smugstyle() {
		if ($this->pictures) {
			include "templates/smugstyle.php";
		}
		else {
			$error = "No Pictures in this album!";
			include "templates/error.php";
		}
	}





	/**
	 * thumbchilds function.
	 * 
	 * @access public
	 * @return void
	 */
	function thumbchilds() {
		include "templates/thumbchilds.php";
		//$this->error_output();
	}





	/**
	 * slideshow function.
	 * 
	 * @access public
	 * @return void
	 */
	function slideshow() {

	}





	/**
	 * wpsrGetChildAlbums function.
	 * 
	 * @access public
	 * @return void
	 */
	function wpsrGetChildAlbums() {
		if ($this->obj->hasChild !== NULL && $this->albums) {
			include "templates/childalbums.php";
		}
	}





	/**
	 * wpsrGetThumbPics function.
	 * 
	 * @access public
	 * @return void
	 */
	function wpsrGetThumbPics() {
		if ($this->pictures) {
			include "templates/thumbpics.php";
		}
	}

	
	
	function addhit($id) {
		
		global $wpdb;
		$sql = $wpdb->query("UPDATE ".WPSR_DB_P." SET hits = hits + 1 WHERE pid = $id LIMIT 1");
		
	}
	


	/**
	 * picture function.
	 * 
	 * @access public
	 * @return void
	 */
	function picture() {
		$this->exif = $this->getexif($this->obj);
		$this->addhit($this->obj->id);
		$this->obj->hits++;

		unset($this->current, $this->maxpic);
		$i = 0;
		foreach ($this->pictures as $navpic) {
			if ($navpic->id == $this->obj->id) {
				$this->current = $i;
			}
			$i++;
		}
		$this->maxpic = $i-1;
		
		$prev = $this->wpsrNavOverlay(-1);
		$next = $this->wpsrNavOverlay(1);

		include "templates/picture.php";
	}
	
	
	
	function getimgsizey() {
		return $this->obj->showsy;
	}


	function getimgsizex() {
		return $this->obj->showsx;
	}
	
	
	function getimgsizes($size) {
		$file = WPSR_FILEPATH.$size.$this->obj->path.$this->obj->file;
		if (file_exists($file)) {
			$imgsize = getimagesize($file);
			$this->obj->showsx = $imgsize[0];
			$this->obj->showsy = $imgsize[1];		
		}
		else {
			$this->obj->showsy = $this->obj->showsx = '';
		}
	}



	/**
	 * wpsrNavPic function.
	 * 
	 * @access public
	 * @param mixed $offset
	 * @param mixed $class. (default: NULL)
	 * @return void
	 */
	function wpsrNavPic($offset, $class = NULL) {
		$navpic = $this->current + $offset;
		if ($navpic >= 0 && $navpic <= $this->maxpic) {
			include "templates/navpic.php";
		}
	}
	
	
	
	/**
	 * wpsrNavPic function.
	 * 
	 * @access public
	 * @param mixed $offset
	 * @return void
	 */
	function wpsrNavOverlay($offset) {
		$navpic = $this->current + $offset;
		if ($navpic >= 0 && $navpic <= $this->maxpic) {
			return $navpic;
		}
		else {
			return -1;
		}
	}





	/**
	 * wpsrBreadcrumbs function.
	 * 
	 * @access public
	 * @return void
	 */
	function wpsrBreadcrumbs($actual = '') {
		include "templates/breadcrumbs.php";
	}





	/**
	 * exif function.
	 * 
	 * @access public
	 * @param object $img
	 * @return array
	 */
	function getexif($img) {
		require 'exif.php';
		$path = WPSR_ORG_FILEPATH.$img->path.$img->file;
		$exif = read_exif_data_raw($path, 0);
		return $exif;
	}





	/**
	 * error_output function.
	 * 
	 * @access public
	 * @return void
	 */
	function error_output() {
/*
		echo "<hr>";
		echo "STYLE: ".$this->style;
		echo "<br />";
		echo "ERROR: ";
		print_r($this->error);
		echo "<br />";
		echo "<br />";
		echo "OBJECT: ";
		echo "<PRE>";
		print_r($this->obj);
		echo "</PRE>";
		echo "<br />";
		echo "<br />";
		echo "PATH: ";
		print_r($this->path);
		echo "<br />";
		echo "<br />";
		echo "ALBUMS: ";
		print_r($this->albums);
		echo "<br />";
		echo "<br />";
		echo "PICTURES: ";
		echo "<PRE>";
		print_r($this->pictures);
		echo "</PRE>";
*/
		$msgs = array_merge(array_unique($this->err()), array_unique($this->msg()));
		$error = "";
		if (count($msgs) > 0) {
			foreach ($msgs as $msg) {
				$error .= $msg.'<br />';
			}
		}
		include "templates/error.php";
	}


}



/**
 * Wordpress Filters & Actions
 */
add_action('init', 'WPsr_flush_rewrite_rules');
add_action('generate_rewrite_rules', 'WPsr_add_rewrite_rules');
add_action('admin_menu', 'WPsr_add_pages');



/**
 * WPsr_flush_rewrite_rules function.
 * 
 * @access public
 * @return void
 */
function WPsr_flush_rewrite_rules() {
	global $wp_rewrite;
	$wp_rewrite->flush_rules();
}


/*
add_filter('page_link', 'WPsr_postlink');
function WPsr_postlink($permalink) {
$permalink = $permalink."asdfasdf";
return $permalink;
}
*/

/**
 * WPsr_add_rewrite_rules function.
 * 
 * @access public
 * @param mixed $wp_rewrite
 * @return void
 */
function WPsr_add_rewrite_rules( $wp_rewrite ) {
	$new_rules = array(
		WPSR_BASE_URI.'/(.+)' => 'index.php?page_id='.WPSR_BASE.'&wpsr='.$wp_rewrite->preg_index(1)
	);
	$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}



/**
 * WPsr_add_pages function.
 * 
 * @access public
 * @return void
 */
function WPsr_add_pages() {
	
	/**
	 * acces_level
	 * 
	 * (default value: 8)
	 * 
	 * @var int
	 * @access public
	 */
	$acces_level = 8;

	$plugin_page = add_menu_page('WPShowroom', 'WPShowroom', $acces_level, __FILE__, 'WPsr_adm1');
	$plugin_page2 = add_submenu_page(__FILE__, 'Upload Pictures', 'Upload Pictures', $acces_level, 'WPsr-pictures', 'WPsr_adm2');
	$plugin_page3 = add_submenu_page(__FILE__, 'Options', 'Options', $acces_level, 'WPsr-options', 'WPsr_adm3');
	add_action( 'admin_head-'. $plugin_page, 'WPsr_add_admin_head' );
	add_action( 'admin_head-'. $plugin_page2, 'WPsr_add_admin_head' );
	add_action( 'admin_head-'. $plugin_page3, 'WPsr_add_admin_head' );
}



/**
 * WPsr_adm1 function.
 * 
 * @access public
 * @return void
 */
function WPsr_adm1() {
	require "wpsr.admin.manage.php";
}



/**
 * WPsr_adm2 function.
 * 
 * @access public
 * @return void
 */
function WPsr_adm2() {
	require "wpsr.admin.pictures.php";
}



/**
 * WPsr_adm3 function.
 * 
 * @access public
 * @return void
 */
function WPsr_adm3() {
	require "wpsr.admin.options.php";
}



/**
 * WPsr_add_admin_head function.
 * 
 * @access public
 * @return void
 */
function WPsr_add_admin_head() {
?>
	<link rel="stylesheet" type="text/css" href="<?php bloginfo('wpurl'); ?>/wp-content/plugins/WPshowroom/admin.css" media="screen" />
	<script type='text/javascript' src='<?php bloginfo('wpurl'); ?>/wp-content/plugins/WPshowroom/mootools-1.2.js'></script>
	<script type='text/javascript' src='<?php bloginfo('wpurl'); ?>/wp-content/plugins/WPshowroom/admin.js'></script>
	<?php
}




/**
 * WPsr_addPID_form function.
 * 
 * @access public
 * @return string
 */
function WPsr_addPID_form() {
	global $wpsr;
	?>
	<input type="hidden" value="<?php echo $wpsr->obj->id; ?>" name="pid" />
	<input type="hidden" value="<?php echo $_SERVER['REQUEST_URI']; ?>" name="redirect_to" />
	<?php
}




/**
 * WPsr_addPID function.
 * 
 * @access public
 * @return int
 */
function WPsr_addPID($comment_ID) {
	global $wpdb;
	
	$pid = (int) $_POST['pid'];
	
	// TODO: wenn pid leer, abfrage, ob parent_comment_id eine pid hat!
	
	if ($pid != '')
	
		$sql = $wpdb->query("UPDATE $wpdb->comments SET pid = '$pid' WHERE comment_ID = '$comment_ID' LIMIT 1");
	
	return $comment_ID;
}
add_action('comment_post','WPsr_addPID');
add_action('trackback_post','WPsr_addPID');
add_action('pingback_post','WPsr_addPID');


function WPsr_comments_template($file = "/WPsr_comments.php") {
	global $wpsr;
	if ($wpsr->style == 2 && count($wpsr->error) < 1) {
		include "templates/comments.php";
	} 
}


function WPsr_get_comments_template( $file = '/comments.php', $separate_comments = false ) {
	global $wp_query, $withcomments, $post, $wpdb, $id, $comment, $user_login, $user_ID, $user_identity, $overridden_cpage, $wpsr;

	if ( ! (is_single() || is_page() || $withcomments) )
		return;

	if ( empty($file) )
		$file = '/comments.php';

	$req = get_option('require_name_email');
	$commenter = wp_get_current_commenter();
	extract($commenter, EXTR_SKIP);

	/** @todo Use API instead of SELECTs. */
	if ( $user_ID) {
		$comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND (comment_approved = '1' OR ( user_id = %d AND comment_approved = '0' ) ) AND pid = %d ORDER BY comment_date_gmt", $post->ID, $user_ID, $wpsr->obj->id));
	} else if ( empty($comment_author) ) {
		$comments = WPsr_get_comments( array('post_id' => $post->ID, 'status' => 'approve', 'order' => 'ASC') );
	} else {
		$comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND ( comment_approved = '1' OR ( comment_author = %s AND comment_author_email = %s AND comment_approved = '0' ) ) AND pid = %d ORDER BY comment_date_gmt", $post->ID, wp_specialchars_decode($comment_author,ENT_QUOTES), $comment_author_email, $wpsr->obj->id));
	}

	// keep $comments for legacy's sake
	$wp_query->comments = apply_filters( 'comments_array', $comments, $post->ID );
	$comments = &$wp_query->comments;
	$wp_query->comment_count = count($wp_query->comments);
	$wpsr->obj->comcount = count($wp_query->comments);
	add_filter('get_comments_number', 'WPsr_get_commentscount');
	
	update_comment_cache($wp_query->comments);

	if ( $separate_comments ) {
		$wp_query->comments_by_type = &separate_comments($comments);
		$comments_by_type = &$wp_query->comments_by_type;
	}

	$overridden_cpage = FALSE;
	if ( '' == get_query_var('cpage') && get_option('page_comments') ) {
		set_query_var( 'cpage', 'newest' == get_option('default_comments_page') ? get_comment_pages_count() : 1 );
		$overridden_cpage = TRUE;
	}

	if ( !defined('COMMENTS_TEMPLATE') || !COMMENTS_TEMPLATE)
		define('COMMENTS_TEMPLATE', true);

	$include = apply_filters('comments_template', STYLESHEETPATH . $file );
	if ( file_exists( $include ) )
		require( $include );
	elseif ( file_exists( TEMPLATEPATH . $file ) )
		require( TEMPLATEPATH .  $file );
	else
		require( get_theme_root() . '/default/comments.php');
}

function WPsr_get_commentscount() {
	global $wpsr;
	return $wpsr->obj->comcount;
}


function WPsr_get_comments( $args = '' ) {
	global $wpdb, $wpsr;

	$defaults = array('status' => '', 'orderby' => 'comment_date_gmt', 'order' => 'DESC', 'number' => '', 'offset' => '', 'post_id' => 0);

	$args = wp_parse_args( $args, $defaults );
	extract( $args, EXTR_SKIP );

	// $args can be whatever, only use the args defined in defaults to compute the key
	$key = md5( serialize( compact(array_keys($defaults)) )  );
	$last_changed = wp_cache_get('last_changed', 'comment');
	if ( !$last_changed ) {
		$last_changed = time();
		wp_cache_set('last_changed', $last_changed, 'comment');
	}
	$cache_key = "get_comments:$key:$last_changed";

	if ( $cache = wp_cache_get( $cache_key, 'comment' ) ) {
		return $cache;
	}

	$post_id = absint($post_id);

	if ( 'hold' == $status )
		$approved = "comment_approved = '0'";
	elseif ( 'approve' == $status )
		$approved = "comment_approved = '1'";
	elseif ( 'spam' == $status )
		$approved = "comment_approved = 'spam'";
	else
		$approved = "( comment_approved = '0' OR comment_approved = '1' )";

	$order = ( 'ASC' == $order ) ? 'ASC' : 'DESC';

	$orderby = 'comment_date_gmt';  // Hard code for now

	$number = absint($number);
	$offset = absint($offset);

	if ( !empty($number) ) {
		if ( $offset )
			$number = 'LIMIT ' . $offset . ',' . $number;
		else
			$number = 'LIMIT ' . $number;

	} else {
		$number = '';
	}

	if ( ! empty($post_id) )
		$post_where = $wpdb->prepare( 'comment_post_ID = %d AND pid = %d AND', $post_id, $wpsr->obj->id );
	else
		$post_where = $wpdb->prepare( 'pid = %d AND', $wpsr->obj->id );

	$comments = $wpdb->get_results( "SELECT * FROM $wpdb->comments WHERE $post_where $approved ORDER BY $orderby $order $number" );
	wp_cache_add( $cache_key, $comments, 'comment' );

	return $comments;
}

?>